package ${package}.web.config;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import ${package}.common.user.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * 登录用户解析
 */
@Slf4j
@Component
public class UserParamResolver implements HandlerMethodArgumentResolver {

    //用户ID-用户
    private Cache<String, UserInfo> userCache = CacheBuilder.newBuilder().expireAfterWrite(10, TimeUnit.MINUTES).maximumSize(100).build();


    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return UserInfo.class.isAssignableFrom(parameter.getParameterType());
    }

    @Override
    public UserInfo resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        String userId = request.getHeader("userId");
        if (StringUtils.isNotEmpty(userId)) {
            UserInfo user = userCache.getIfPresent(userId);
            if (user == null) {
                //此处查询用户
                // if (userInfo.isSuccess()) {
                //     UserInfoBean data = userInfo.getData();
                //     userCache.put(userId, data);
                //     return data;
                // } else {
                //     log.error("查不到用户:{}", userId);
                // }
            } else {
                return user;
            }
        }
        return null;
    }

    public UserInfo getUser(String userId) {
        return userCache.getIfPresent(userId);
    }

}
